package com.bulletelc.apollopre.module.main.cart;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.CartListBean;
import com.bulletelc.apollopre.entity.OrderConfirmBean;
import com.bulletelc.apollopre.entity.WxShareBean;
import com.bulletelc.apollopre.eventbus.EventBusEvent;
import com.bulletelc.apollopre.framework.MVPBaseFragment;
import com.bulletelc.apollopre.interfaces.listener.OnCartCheckBoxChangeListener;
import com.bulletelc.apollopre.interfaces.listener.OnCartCountChangeListener;
import com.bulletelc.apollopre.module.deal.clearing.ClearingActivity;
import com.bulletelc.apollopre.module.main.MainActivity;
import com.bulletelc.apollopre.module.user.LoginMainActivity;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author: lhl
 * time  : 2017/10/15
 * desc  : 购物车界面
 */

public class CartFragment extends MVPBaseFragment<CartContract.View, CartPresenter> implements CartContract.View,
        View.OnClickListener, CompoundButton.OnCheckedChangeListener, OnCartCountChangeListener, OnCartCheckBoxChangeListener,
        OnRefreshListener {
    // views
    private ToggleButton tBtnEdit;
    private SmartRefreshLayout srlCartContent;
    private RelativeLayout rlNoContent;
    private RelativeLayout rlNoLogin;
    private TextView tvGoToMall;
    private RelativeLayout rlOrderCount;
    private ExpandableListView elvCartList;
    private CheckBox cbSelAll;
    private LinearLayout tvPayHint;
    private TextView tvCountMoney;
    private TextView tvShare;
    private TextView tvCartCount;
    private TextView tvInstallFee;
    private Button btnGoClosing;
    private ProgressBar pbLoad;
    private Button btnGoToLogin;

    // data
    private CartListAdapter cartListAdapter;
    private List<CartListBean> cartListBeans;
    private boolean edit = false; // 标识是否编辑状态，True为编辑，默认False
    private double totalPrice = 0; // 总价
    private double totalInstallFee = 0; // 安装总价
    private String cid; // 购物车ID
    private List<Integer> cartItemIds; // 购物车商品ID

    @Override
    public void onStart() {
        super.onStart();
        initCardList();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getLayoutRes() {
        return R.layout.cart_fragment;
    }

    @Override
    public void assignViews() {
        tvCartCount = findView(R.id.tvCartCount);
        tvShare = findView(R.id.tvShare);
        srlCartContent = findView(R.id.srlCartContent);
        tBtnEdit = findView(R.id.tBtnEdit);
        rlNoLogin = findView(R.id.rlNoLogin);
        rlNoContent = findView(R.id.rlNoContent);
        tvGoToMall = findView(R.id.tvGoToMall);
        rlOrderCount = findView(R.id.rlOrderCount);
        elvCartList = findView(R.id.elvCartList);
        cbSelAll = findView(R.id.cbSelAll);
        tvPayHint = findView(R.id.tvPayHint);
        tvCountMoney = findView(R.id.tvCountMoney);
        tvInstallFee = findView(R.id.tvInstallFee);
        btnGoClosing = findView(R.id.btnGoClosing);
        btnGoToLogin = findView(R.id.btnGoToLogin);
        pbLoad = findView(R.id.pbLoad);
    }

    @Override
    public void setListener() {
        tBtnEdit.setOnCheckedChangeListener(this);
        btnGoClosing.setOnClickListener(this);
        cbSelAll.setOnClickListener(this);
        btnGoToLogin.setOnClickListener(this);
        tvGoToMall.setOnClickListener(this);
        tvShare.setOnClickListener(this);
        srlCartContent.setOnRefreshListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        cartListBeans = new ArrayList<>();
        cartListAdapter = new CartListAdapter(baseActivity, cartListBeans);
        cartListAdapter.setCountChangeListener(this);
        cartListAdapter.setCheckBoxChangeListener(this);
        elvCartList.setAdapter(cartListAdapter);
    }

    @Override
    protected CartPresenter createPresenter() {
        return new CartPresenter();
    }

    @Override
    public void onSuccessCartList(List<CartListBean> cartListBeans) {
        List<CartListBean> filterCartListBeans = filterCartListBeans(cartListBeans);
        if (filterCartListBeans != null && filterCartListBeans.size() > 0) {
            this.cartListBeans.clear();
            this.cartListBeans.addAll(filterCartListBeans(cartListBeans));
            tvCartCount.setText("购物车(" + getCartListCount(this.cartListBeans) + ")"); // 设置购物车数量
            expandListView(); // 展开
            cartListAdapter.notifyDataSetChanged();
            cbSelAll.setChecked(isAllCheck()); // 默认全选
            cid = filterCartListBeans.get(0).getProduct_list().get(0).getCart_id(); // 设置购物车ID
            showTotalPrice(); // 显示总价
            showHaveCartListViews(); // 显示购物车有内容的样子
        } else {
            // 购物车没有数据
            showView(rlNoContent);
            tvCartCount.setText("购物车");
        }
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onFailCartList(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
        MyUtil.setProgressBar(pbLoad, false);
        showView(srlCartContent);
    }

    @Override
    public void onErrorCartList(String error) {
        ToastUtil.showLongToast(getActivity(), R.string.network_msg);
        MyUtil.setProgressBar(pbLoad, false);
        showView(srlCartContent);
    }

    @Override
    public void onSuccessCountChange(boolean isAdd, int groupPosition, int childPosition, boolean isChecked) {
        CartListBean.CartProductListBean cartProductListBean = cartListBeans.get(groupPosition).getProduct_list().get(childPosition);
        if (isAdd) {
            cartListBeans.get(groupPosition).getProduct_list().get(childPosition).setQuantity(cartProductListBean.getQuantity() + 1);
        } else {
            cartListBeans.get(groupPosition).getProduct_list().get(childPosition).setQuantity(cartProductListBean.getQuantity() - 1);
        }
        cartListAdapter.notifyDataSetChanged();
        if (isChecked) {
            showTotalPrice();
        }

    }

    @Override
    public void onFailCountChange(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorCountChange(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccessDeleteCart() {
        Toast.makeText(baseActivity, "删除成功", Toast.LENGTH_SHORT).show();
        //deleteCartLocal();
        presenter.getCartList(MyApplication.getToken());
    }

    @Override
    public void onFailDeleteCart(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorDeleteCart(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccessClearing(OrderConfirmBean confirmBean) {
        if (confirmBean != null) {
            Intent intent = new Intent(baseActivity, ClearingActivity.class);
            intent.putExtra(IntentCode.EXTRA_KEY_CONFIRM_ORDER_DATA, confirmBean);
            startActivity(intent);
        } else {
            Toast.makeText(baseActivity, "数据有误", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onFailClearing(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorClearing(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccessCreateCartShare(WxShareBean wxShareBean) {
        ((MainActivity) baseActivity).showCartDialog(wxShareBean);
        presenter.shareCallback(cid);
    }

    @Override
    public void onFailCreateCartShare(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorCreateCartShare(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccessShareCart(boolean b) {
    }

    @Override
    public void onFailShareCart(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorShareCart(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btnGoClosing:
                if (edit) {
                    deleteCart(); // 走删除
                } else {
                    clearing(); // 走结算
                }
                break;

            case R.id.cbSelAll:
                setAllCheck(((CheckBox) v).isChecked()); // 全选
                break;

            case R.id.btnGoToLogin:
                Intent intentLogin = new Intent(baseActivity, LoginMainActivity.class); // 跳到登录界面
                startActivity(intentLogin);
                break;

            case R.id.tvGoToMall:
                Intent intent = new Intent(baseActivity, MainActivity.class); // 去逛逛
                intent.putExtra(IntentCode.EXTRA_KEY_FRAGMENT_POSITION, 0);
                startActivity(intent);
                break;

            case R.id.tvShare:
                presenter.createCartShare(cid);
                break;
        }
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.tBtnEdit: //编辑
                edit = isChecked;
                if (isChecked) {
                    btnGoClosing.setText("删除");
                    tvPayHint.setVisibility(View.GONE);
                    tvCountMoney.setVisibility(View.GONE);
                } else {
                    btnGoClosing.setText("结算");
                    tvPayHint.setVisibility(View.VISIBLE);
                    tvCountMoney.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    @Override
    public void onCountAdd(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        int num = Integer.valueOf(((TextView) showCountView).getText().toString());
        num++;
        presenter.addCount(getJson(num, groupPosition, childPosition), MyApplication.getToken(), groupPosition, childPosition, isChecked);

    }

    @Override
    public void onCountReduce(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        int num = Integer.valueOf(((TextView) showCountView).getText().toString());
        if (num > 1) {
            num--;
            presenter.reduceCount(getJson(num, groupPosition, childPosition), MyApplication.getToken(), groupPosition, childPosition, isChecked);
        }
    }

    @Override
    public void onGroupCheck(int groupPosition, boolean isChecked) {
        groupCheck(groupPosition, isChecked);
    }

    @Override
    public void onChildCheck(int groupPosition, int childPosition, boolean isChecked) {
        childCheck(groupPosition, childPosition, isChecked);
    }

    /**
     * 接收处理事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEvent event) {
        //LogUtil.i("event.errCode=" + event.getWxPayErrCode());
    }

    /**
     * 将listView的子listView展开
     */
    private void expandListView() {
        for (int i = 0, size = cartListAdapter.getGroupCount(); i < size; i++) {
            elvCartList.expandGroup(i);
        }
    }

    /**
     * 获取添加到购物车所需要的json参数
     *
     * @return
     */
    private String getJson(int num, int groupPosition, int childPosition) {
        CartListBean.CartProductListBean cartProductListBean = cartListBeans.get(groupPosition).getProduct_list().get(childPosition);
        String json = null;
        JSONObject object = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONObject subObject = new JSONObject();
        try {
            subObject.put("buy_num", num);
            subObject.put("cart_item_id", cartProductListBean.getId());//购物车子项id
            subObject.put("product_id", cartProductListBean.getProduct_id());//商品ID
            subObject.put("product_sku_id", cartProductListBean.getProduct_sku_id());//商品规格id
            subObject.put("supplier_id", cartProductListBean.getSupplier_id());//供应商id
            subObject.put("is_install", cartProductListBean.getIs_install());//供应商id
            jsonArray.put(0, subObject);
            object.put("cart_item", jsonArray);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 过滤掉空child数据
     *
     * @param cartListBeans
     * @return
     */
    private List<CartListBean> filterCartListBeans(List<CartListBean> cartListBeans) {
        List<CartListBean> filterCartLists = new ArrayList<>();
        if (cartListBeans != null) {
            for (int i = 0, size = cartListBeans.size(); i < size; i++) {
                CartListBean cartListBean = cartListBeans.get(i);
                if (cartListBean.getProduct_list().size() > 0) {
                    filterCartLists.add(cartListBean);
                }
            }
        }
        return filterCartLists;
    }

    /**
     * 点击全选按钮, 所有checkbox全选/全不选
     *
     * @param isCheck
     */
    private void setAllCheck(boolean isCheck) {
        for (int i = 0, size = cartListBeans.size(); i < size; i++) {
            List<CartListBean.CartProductListBean> cartProductListBeans = cartListBeans.get(i).getProduct_list();
            cartListBeans.get(i).setChecked(isCheck);
            for (int j = 0, sizeJ = cartProductListBeans.size(); j < sizeJ; j++) {
                cartListBeans.get(i).getProduct_list().get(j).setChecked(isCheck);
            }
        }
        cartListAdapter.notifyDataSetChanged();
        showTotalPrice();
    }

    /**
     * 判断是否所有的checkbox全选
     */
    private boolean isAllCheck() {
        for (int i = 0, size = cartListBeans.size(); i < size; i++) {
            if (!cartListBeans.get(i).isChecked()) {
                return false;
            }
            for (int j = 0, sizeJ = cartListBeans.get(i).getProduct_list().size(); j < sizeJ; j++) {
                if (!cartListBeans.get(i).getProduct_list().get(j).isChecked()) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * group的checkbox选中/不选中
     *
     * @param groupPosition
     * @param isChecked
     */
    private void groupCheck(int groupPosition, boolean isChecked) {
        cartListBeans.get(groupPosition).setChecked(isChecked);
        for (int i = 0, size = cartListBeans.get(groupPosition).getProduct_list().size(); i < size; i++) {
            cartListBeans.get(groupPosition).getProduct_list().get(i).setChecked(isChecked);
        }
        cbSelAll.setChecked(isAllCheck());
        cartListAdapter.notifyDataSetChanged();
        showTotalPrice();
    }

    /**
     * child的checkbox选中/不选中
     *
     * @param groupPosition
     * @param childPosition
     * @param isChecked
     */
    private void childCheck(int groupPosition, int childPosition, boolean isChecked) {
        cartListBeans.get(groupPosition).getProduct_list().get(childPosition).setChecked(isChecked);
        cartListBeans.get(groupPosition).setChecked(isChildAllCheck(groupPosition));
        cbSelAll.setChecked(isAllCheck());
        cartListAdapter.notifyDataSetChanged();
        showTotalPrice();
    }

    /**
     * 判断指定条目中的子数据中是否所有的CheckBox都选中。
     *
     * @param groupPosition
     * @return
     */
    private boolean isChildAllCheck(int groupPosition) {
        for (int i = 0, size = cartListBeans.get(groupPosition).getProduct_list().size(); i < size; i++) {
            if (!cartListBeans.get(groupPosition).getProduct_list().get(i).isChecked()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 计算显示总价格
     */
    private void showTotalPrice() {
        totalPrice = 0;
        totalInstallFee = 0;
        //计算总价钱
        for (int i = 0, size = cartListBeans.size(); i < size; i++) {
            for (int j = 0, sizeJ = cartListBeans.get(i).getProduct_list().size(); j < sizeJ; j++) {
                CartListBean.CartProductListBean bean = cartListBeans.get(i).getProduct_list().get(j);
                if (bean.isChecked()) {
                    totalInstallFee += bean.getInstall_fee() * bean.getQuantity();
                    totalPrice += bean.getPrice() * bean.getQuantity();
                }
            }
        }

        //显示总安装费
        tvInstallFee.setText("¥" + MyUtil.format2(totalInstallFee));
        //显示总价钱
        tvCountMoney.setText("¥" + MyUtil.format2(totalPrice + totalInstallFee));
    }

    /**
     * 删除购物车
     */
    private void deleteCart() {
        cartItemIds = new ArrayList<>();
        for (int i = 0, size = cartListBeans.size(); i < size; i++) {
            for (int j = 0, sizeJ = cartListBeans.get(i).getProduct_list().size(); j < sizeJ; j++) {
                CartListBean.CartProductListBean bean = cartListBeans.get(i).getProduct_list().get(j);
                if (bean.isChecked()) {
                    cartItemIds.add(Integer.valueOf(bean.getId()));
                }
            }
        }

        if (cartItemIds.size() > 0) {
            JSONObject object = new JSONObject();
            JSONArray array = new JSONArray();
            for (int i = 0, size = cartItemIds.size(); i < size; i++) {
                array.put(cartItemIds.get(i));
            }
            String json = null;
            try {
                object.put("cart_item_id", array);
                json = object.toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            presenter.deleteCart(json, MyApplication.getToken());
            tBtnEdit.setChecked(false);
        } else {
            Toast.makeText(baseActivity, "请选中商品", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 本地更新购物车删除数据
     */
    private void deleteCartLocal() {
        for (int i = 0, size = cartItemIds.size(); i < size; i++) {
            String cartItemId = cartItemIds.get(i).toString();
            for (int j = 0, sizeJ = cartListBeans.size(); j < sizeJ; j++) {
                for (int z = 0, sizeZ = cartListBeans.get(j).getProduct_list().size(); z < sizeZ; z++) {
                    if (cartItemId.equals(cartListBeans.get(j).getProduct_list().get(z).getId())) {
                        cartListBeans.get(j).getProduct_list().remove(z);
                    }
                }
            }
        }
        List<CartListBean> filterCartList = filterCartListBeans(cartListBeans);
        if (filterCartList.size() > 0) {
            cartListBeans.clear();
            cartListBeans.addAll(filterCartList);
            cartListAdapter.notifyDataSetChanged();
        } else if (filterCartList.size() == 0) {
            showView(rlNoContent);
        }
    }

    /**
     * 去结算
     */
    private void clearing() {
        JSONObject object = new JSONObject();
        try {
            JSONArray array = new JSONArray();
            for (int i = 0, size = cartListBeans.size(); i < size; i++) {
                JSONObject itemObject = new JSONObject();
                JSONArray itemIdArray = new JSONArray();
                for (int j = 0, sizeJ = cartListBeans.get(i).getProduct_list().size(); j < sizeJ; j++) {
                    CartListBean.CartProductListBean bean = cartListBeans.get(i).getProduct_list().get(j);
                    if (bean.isChecked()) {
                        itemIdArray.put(Integer.valueOf(bean.getId()));
                    }
                }
                if (itemIdArray.length() > 0) {
                    itemObject.put("supplier_id", Integer.valueOf(cartListBeans.get(i).getSupplier_id()));
                    itemObject.put("cart_item_id", itemIdArray);
                    array.put(itemObject);
                }
            }
            if (array.length() > 0) {
                object.put("cart_item_list", array);
                object.put("eshop_id", 1);
            } else {
                Toast.makeText(baseActivity, "请选择商品", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String json = object.toString();

        presenter.clearing(json, MyApplication.getToken());
    }

    /**
     * 计算购物车件数
     */
    private int getCartListCount(List<CartListBean> listBeans) {
        int count = 0;
        if (listBeans != null && listBeans.size() > 0) {
            for (int i = 0; i < listBeans.size(); i++) {
                count += listBeans.get(i).getProduct_list().size();
            }
        }
        return count;
    }

    /**
     * 显示指定View
     * @param v
     */
    private void showView(View v) {
        rlNoContent.setVisibility(View.GONE);
        srlCartContent.setVisibility(View.GONE);
        rlOrderCount.setVisibility(View.GONE);
        tBtnEdit.setVisibility(View.GONE);
        tvShare.setVisibility(View.GONE);
        rlNoLogin.setVerticalGravity(View.GONE);
        v.setVisibility(View.VISIBLE);
    }

    /**
     * 显示购物车内容
     */
    private void showHaveCartListViews() {
        rlOrderCount.setVisibility(View.VISIBLE);
        tBtnEdit.setVisibility(View.VISIBLE);
        srlCartContent.setVisibility(View.VISIBLE);
        tvShare.setVisibility(View.VISIBLE);
        rlNoContent.setVisibility(View.GONE);
        rlNoLogin.setVisibility(View.GONE);
        tBtnEdit.setEnabled(true);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        srlCartContent.finishRefresh(200);
        initCardList();
    }

    /**
     * 初始化购物车
     */
    private void initCardList() {
        String token = MyApplication.getToken();
        if (token != null && token.length() > 0) {
            MyUtil.setProgressBar(pbLoad, true);
            rlNoLogin.setVisibility(View.GONE);
            presenter.getCartList(token);
        } else {//未登录
            showView(rlNoLogin);
        }
    }

}
